/*
 * Copyright (C) 2012 CyberAgent
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *//*


package com.imay.live.activity.video;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.imay.live.Constants;
import com.imay.live.activity.dynamics.ReleaseActivity;
import com.imay.videorecord.MagicEngine;
import com.imay.videorecord.R;
import com.imay.videorecord.activity.VideoClipActivity;
import com.imay.videorecord.adapter.FilterAdapter;
import com.imay.videorecord.camera.CameraEngine;
import com.imay.videorecord.camera.utils.CameraUtils;
import com.imay.videorecord.encoder.edit.VideoEditor;
import com.imay.videorecord.encoder.view.MagicCameraView;
import com.imay.videorecord.encoder.view.RecordStatusListener;
import com.imay.videorecord.filter.helper.MagicFilterType;
import com.imay.videorecord.fragment.LoadingDialogFragment;
import com.imay.videorecord.utils.AudioPermissionUtil;
import com.imay.videorecord.utils.ImayCons;
import com.imay.videorecord.utils.ImayParams;
import com.imay.videorecord.utils.ImayUtils;
import com.imay.videorecord.utils.MagicFilterTools;
import com.imay.videorecord.utils.PermissionUtil;
import com.imay.videorecord.view.AutoAdjustItemClickListener;
import com.imay.videorecord.view.AutoAdjustRecylerView;
import com.imay.videorecord.view.VideoProgressView;

import java.util.ArrayList;
import java.util.List;


public class VideoRecordActivity extends Activity implements OnClickListener, View.OnLongClickListener, RecordStatusListener {

    private final String TAG = VideoRecordActivity.class.getSimpleName();

    private Context mContxt;

    private ImageView btn_redord, mIvFlash, iv_switch_camera, btn_ok;
    private AutoAdjustRecylerView mRecyclerView;
    private ImageView mIvFocus, mIvClose;
    private TextView mTvRecordTime, tv_note;

    private MagicFilterTools mFilterTools;
    private FilterAdapter mAdapter;
    private MagicEngine mMagicEngine;

    // 监听操作
    private MagicCameraView mCameraView;
    private int mFlashMode;

    // 录制视频
    private boolean isRecording = false; // 录制状态
    private boolean recordFinish = false;
    private boolean muxering = true; // 监听是否已经写入完毕
    private int progressStatus = 0;

    private int CAMERA_TYPE = 0;

    // 监听控件是长按还是点击
    private int clickType = -1;

    */
/**
     * ==========跳转==========
     *//*

    private final int REQUEST_PICK_VIDEO = 1;
    private final int REQUEST_CLIP_VIDEO = 2;

    */
/**
     * ==========视频拼接模块============
     *//*

    private String imagePath; // 图片路径
    private String videoUrl; // 视频路径
    private String videoName;

    private VideoProgressView mProgressView;

    private VideoEditor editor;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mContxt = this;

        Point screenSize = new Point();
        getWindowManager().getDefaultDisplay().getSize(screenSize);

        // 获取屏幕宽度
        ImayCons.screenW = screenSize.x;
        ImayCons.screenH = screenSize.y;

        setContentView(R.layout.activity_video_record);

        // 开启是否前置摄像
        CAMERA_TYPE = getIntent().getIntExtra(ImayCons.KEY_CAMERA_TYPE, 0);
        if (CAMERA_TYPE == ImayCons.CAMERA_IS_ID_CARD) {
            ImayParams.IS_ID_CARD_CAMERA = true;
        } else {
            ImayParams.IS_ID_CARD_CAMERA = false;
        }
        ImayParams.OPEN_CAMERA_ID = CAMERA_TYPE;

        initPermission();
        initData();
        initView();
        initListener();
    }

    private void initPermission() {
        */
/**
         * 权限控制
         *//*

        List<String> permissionList = new ArrayList<>();
        if (!PermissionUtil.selfPermissionGranted(this, Manifest.permission.CAMERA)) {
            permissionList.add(Manifest.permission.CAMERA);
        }
        if (!PermissionUtil.selfPermissionGranted(this, Manifest.permission.RECORD_AUDIO)) {
            permissionList.add(Manifest.permission.RECORD_AUDIO);
        }
        if (!PermissionUtil.selfPermissionGranted(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (!PermissionUtil.selfPermissionGranted(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (!permissionList.isEmpty()) {
            String[] permissions = new String[permissionList.size()];
            permissionList.toArray(permissions);
            ActivityCompat.requestPermissions(this, permissions,
                    1);
        }

        //注册广播
        registerReceiver(mHomeKeyEventReceiver, new IntentFilter(
                Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                if (permissions[i].equals(Manifest.permission.CAMERA)) {
                    int status = grantResults[i];
                    if (status == 0) {
                        */
/**
                         * 当相机因第一次无法获取权限异常open时返回false信息，进行activty的重启操作
                         * 360手机无限请求权限bug
                         *//*

                        //recreate();
                    } else if (status == -1) {
                        Toast.makeText(this, getString(R.string.message_denied), Toast.LENGTH_SHORT).show();
                        finish();
                    }
                    break;
                }
            }
        }
    }

    private void initData() {
        editor = new VideoEditor(this);
    }

    // 监听事件
    private void initListener() {
        btn_redord.setOnClickListener(this);
        btn_redord.setOnLongClickListener(this);
        btn_redord.getMeasuredWidth();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            btn_redord.getMaxHeight();
        }
        btn_redord.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (view.getId() == R.id.btn_redord) {
                    final int width = btn_redord.getMeasuredWidth();
                    final int height = btn_redord.getMeasuredHeight();
                    double y = motionEvent.getY();
                    double x = motionEvent.getX();
                    if (x < 0 || x > width || y < 0 || y > height) {
                        if (isRecording) {
                            stopRecording();
                            return true; // 不给child或者其他事件获取
                        }
                    }
                }
                return false;
            }
        });

        // 录制按钮
        btn_ok.setOnClickListener(this); // 提交
        mIvFlash.setOnClickListener(this); // 闪光灯
        iv_switch_camera.setOnClickListener(this); // 摄像头
        mIvClose.setOnClickListener(this); //

        // 滤镜选择
        mRecyclerView.setItemClickListener(new AutoAdjustItemClickListener() {
            @Override
            public void onItemClick(View view, int postion) {
                if (!isRecording) {
                    updateFilter(postion);
                }
            }
        });

        // 动作监听
        mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleGestureListener());
        mGestureDetetor = new GestureDetector(this, new GestureDetetor());
        mCameraView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                if (event.getPointerCount() == 1) {
                    mGestureDetetor.onTouchEvent(event);
                } else {
                    mScaleGestureDetector.onTouchEvent(event);
                }
                return true;
            }
        });

        // 视频监听操作
        mCameraView.setRecordListener(this);
    }

    // 控件信息
    private void initView() {
        // 播放器
        MagicEngine.Builder builder = new MagicEngine.Builder();
        mCameraView = (MagicCameraView) findViewById(R.id.glsurfaceview_camera);
        mMagicEngine = builder.build(mCameraView);

        // 录制按钮init及listener
        btn_redord = (ImageView) findViewById(R.id.btn_redord);
        // 确认按钮init及listener
        btn_ok = (ImageView) findViewById(R.id.btn_ok);
        // 照片文件按钮
        findViewById(R.id.btn_photo).setOnClickListener(this);
        // focus
        mIvFocus = (ImageView) findViewById(R.id.iv_focus);
        // iv_close
        mIvClose = (ImageView) findViewById(R.id.iv_close);
        // 滤镜init
        mFilterTools = MagicFilterTools.getInstance(mContxt);
        // 滤镜选择
        mRecyclerView = (AutoAdjustRecylerView) findViewById(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayout.HORIZONTAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setPxPerMillsec(1.0f);
        mAdapter = new FilterAdapter(this, mRecyclerView);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setNames(mFilterTools.getFilterNames(mContxt));
        mAdapter.notifyDataSetChanged();


        //iv_flash闪光灯
        mIvFlash = (ImageView) findViewById(R.id.iv_flash);

        // 摄像头切换
        iv_switch_camera = (ImageView) findViewById(R.id.iv_switch_camera);

        // 录制时间
        mTvRecordTime = (TextView) findViewById(R.id.tv_record_time);
        mTvRecordTime.setText("60.0");

        RelativeLayout rl_content = (RelativeLayout) findViewById(R.id.rl_content);
        rl_content.setLayoutParams(new LinearLayout.LayoutParams(ImayCons.screenW, ImayCons.screenW));

        mProgressView = (VideoProgressView) findViewById(R.id.recorder_progress);

        tv_note = (TextView) findViewById(R.id.tv_note);
    }

    // 切换滤镜
    private void updateFilter(int position) {
        MagicFilterType filterType = mFilterTools.getFilterType(position);
        mMagicEngine.setFilter(filterType);

        mAdapter.setSelectedPostion(position);
        mRecyclerView.checkAutoAdjust(position);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            mCameraView.resumeCamera();
        } catch (Exception e) {

        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            pauseRecord();
            mCameraView.pauceCamera();
        } catch (Exception e) {

        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMagicEngine = null;
        mCameraView.release();
        mCameraView = null;
        mRecyclerView = null;
        mAdapter = null;
        CameraEngine.onDestroy();
        CameraUtils.currentScreenSize = null;
        if (mHomeKeyEventReceiver != null) {
            unregisterReceiver(mHomeKeyEventReceiver);
        }
        Runtime.getRuntime().gc();
    }


    // 锁屏停止录制
    private void pauseRecord() {
        if (isRecording) {
            isRecording = false;
            mMagicEngine.stopRecord();
            btn_ok.setVisibility(View.VISIBLE);
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0: // 进度条回显
                    if (isRecording) {
                        int m = 600 - progressStatus;
                        mTvRecordTime.setText(m / 10f + "");
                    }
                    if (progressStatus >= 30) {
                        btn_ok.setVisibility(View.VISIBLE);
                        btn_ok.setClickable(true);
                    } else {
                        btn_ok.setVisibility(View.INVISIBLE);
                        btn_ok.setClickable(false);
                    }
                    break;
                case 1: // 跳转至剪辑页面
                    Intent intent = new Intent(VideoRecordActivity.this, VideoClipActivity.class);
                    intent.putExtra(ImayParams.fileUri, (String) msg.obj);
                    startActivityForResult(intent, REQUEST_CLIP_VIDEO);
                    break;
                case 2: //
//                    Bundle bundle = new Bundle();
//                    bundle.putString(ImayParams.movUri, videoUrl);
//                    bundle.putString(ImayParams.imgUri, imagePath);
//                    getIntent().putExtras(bundle);
//                    setResult(RESULT_OK, getIntent());
//                    finish();
                    ReleaseActivity.startActivity(VideoRecordActivity.this, imagePath, videoUrl, null, ReleaseActivity.MOVIE, Constants.DYNAMICSFEED_REQUEST_CODE);
                    break;
                case 3:
                    // stop
                    isRecording = false;
                    recordFinish = true;
                    mRecyclerView.setClickable(true);
                    btn_redord.setSelected(false);
                    btn_redord.setPressed(false);
                    mMagicEngine.stopRecord();
                    mTvRecordTime.setText("0.0");
                    btn_ok.setVisibility(View.VISIBLE);
                    break;
                case 4:
                    // 删除
                    ImayUtils.deleteMovFile(mContxt, videoUrl);
                    progressStatus = 0;
                    mProgressView.setCurrentState(VideoProgressView.State.DELETE);
                    mProgressView.clearTimeList();
                case 5: // 返回到首页
                    LoadingDialogFragment.setWasSpinning();
                    break;
                case 6:
                    finish();
                    break;
            }
        }
    };

    */
/**
     * 开始录制
     *//*

    private void startRecording() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        mMagicEngine.setFlashMode(mFlashMode);
        isRecording = true;
        recordFinish = false;
        mRecyclerView.setClickable(false);
        // 开始录制
        if (AudioPermissionUtil.getinstance().isHasAudioRecordingPermission(this.getApplicationContext())) {
            mMagicEngine.startRecord(true);
        } else {
            mMagicEngine.startRecord(false);
        }
    }

    */
/**
     * 停止录制
     *//*

    private void stopRecording() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
        // 停止录制
        mMagicEngine.setFlashMode(0);
        isRecording = false;
        mRecyclerView.setClickable(true);
        mMagicEngine.stopRecord();
    }

    @Override
    public void onClick(final View v) {
        int id = v.getId();
        if (id == R.id.btn_redord) {
            if (isRecording) {
                btn_redord.setSelected(false);
                stopRecording();
            } else {
                btn_redord.setSelected(true);
                startRecording();
            }
        } else if (id == R.id.iv_switch_camera) {
            if (!isRecording) {
                mCameraView.switchCamera();
                setViewFlasMode();
            }
        } else if (id == R.id.btn_photo) {
            if (!isRecording) {
                Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                photoPickerIntent.setType("video*/
/*");
                startActivityForResult(photoPickerIntent, REQUEST_PICK_VIDEO);
            }
        } else if (id == R.id.btn_ok) {
            if (isRecording) { // 正在录制时需暂停
                stopRecording();
            }
            clickOk();
        } else if (id == R.id.iv_close) {  //关闭录像
            onBackPressed();
        } else if (id == R.id.iv_flash) {
            if (!isRecording) {
                setFlashMode();
            }
        }
    }

    private void setFlashMode() {
        if (mFlashMode > 0) {
            mFlashMode = 0;
        } else {
            mFlashMode = mFlashMode + 1;
        }
        setViewFlasMode();
    }

    private void setViewFlasMode() {
        if (CameraEngine.getCameraInfo().isFront) {//前置摄像头，不可用
            mMagicEngine.setFlashMode(0);
            mIvFlash.setImageResource(R.mipmap.btn_flash_off);
            mIvFlash.setEnabled(false);
            mIvFlash.setImageResource(R.mipmap.btn_flash_ban);
        } else {
            mIvFlash.setEnabled(true);
            if (mFlashMode == 1) {
                mIvFlash.setImageResource(R.mipmap.btn_flash_on);
            } else {
                mIvFlash.setImageResource(R.mipmap.btn_flash_off);
            }
        }
    }

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        */
/**
         * 重塑
         *//*

        updateFilter(0);
        if (requestCode == REQUEST_PICK_VIDEO) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    Message msg = new Message();
                    msg.what = 1; // clip
                    msg.obj = data.getData().toString();
                    mHandler.sendMessage(msg);
                }
            }
        } else if (requestCode == REQUEST_CLIP_VIDEO) {
            if (resultCode == RESULT_OK) {
                Bundle bundle = new Bundle();
                bundle.putString(ImayParams.movUri, data.getStringExtra(ImayParams.movUri));
                bundle.putString(ImayParams.imgUri, data.getStringExtra(ImayParams.imgUri));
                getIntent().putExtras(bundle);
                setResult(RESULT_OK, getIntent());
                finish();
            }
        }
    }

    @Override
    public boolean onLongClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_redord) {
            clickType = 1;
            if (!isRecording) {
                startRecording();
            }
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        if (isRecording) {
            stopRecording();
        }
        ImayUtils.deleteMovFile(mContxt, videoUrl);
        super.onBackPressed();
    }

    */
/**
     * =======手势========
     *//*

    private ScaleGestureDetector mScaleGestureDetector;
    private GestureDetector mGestureDetetor;
    private State state;
    private int mFocusX;
    private int mFocusY;

    private enum State {NONE, DRAG, ZOOM, FLING, ANIMATE_ZOOM}

    */
/**
     * 缩放监听
     *//*

    public class ScaleGestureListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        private float scale = 0;

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            if (detector.getScaleFactor() > 1)//放大
                scale = 1;
            else
                scale = -2;
            CameraEngine.setZoom(scale);
            return true;
        }

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            setState(State.ZOOM);
            return true;    // 一定要返回true才会进入onScale()这个函数
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
            setState(State.NONE);
        }
    }

    */
/**
     * 监听拖拽滑动
     *//*

    public class GestureDetetor extends GestureDetector.SimpleOnGestureListener {

        private static final int FLING_MIN_DISTANCE = 100;
        private static final int FLING_MIN_VELOCITY = 0;

        @Override
        public boolean onDown(MotionEvent motionEvent) {
            setState(State.DRAG);
            return false;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent event) {
            if (state == State.DRAG) {
                mFocusX = (int) event.getX();
                mFocusY = (int) event.getY();
                handleFocusMetering(event);    //自动对焦
            }
            setState(State.NONE);
            return super.onSingleTapConfirmed(event);
        }

        //猛滑动
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            if (!isRecording) {
                if (state == State.DRAG) {
                    int pos = mAdapter.getSelectedPostion();
                    if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
                            && Math.abs(velocityX) > FLING_MIN_VELOCITY
                            && pos < mAdapter.getItemCount() - 1) { //左滑
                        pos = pos + 1;
                        updateFilter(pos);
                    } else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
                            && Math.abs(velocityX) > FLING_MIN_VELOCITY
                            && pos > 0) { //右滑
                        pos = pos - 1;
                        updateFilter(pos);
                    }
                }
            }
            return true;
        }
    }

    private int clamp(int x, int min, int max) {
        if (x > max) {
            return max;
        }
        if (x < min) {
            return min;
        }
        return x;
    }

    */
/**
     * 聚焦
     *
     * @param x
     * @param y
     * @param coefficient
     * @return
     *//*

    private Rect calculateTapArea(float x, float y, float coefficient) {
        float focusAreaSize = 100;
        int areaSize = Float.valueOf(focusAreaSize * coefficient).intValue();

        // 获取屏幕中点
        int centerScreenX = ImayCons.screenW / 2;
        int centerScreenY = ImayCons.screenW / 2;

        // 计算以屏幕的中点的触点坐标
        int centerScreenTouchX = (int) (x - centerScreenX);
        int centerScreenTouchY = (int) (y - centerScreenY);

        // 以相机对焦为X(-1000,1000),Y(-1000,1000)的二维坐标中按比例计算对焦的坐标
        int centerX = (centerScreenTouchX * 1000) / centerScreenX;
        int centerY = (centerScreenTouchY * 1000) / centerScreenY;

        int left = clamp(centerX - areaSize / 2, -1000, 1000);
        int right = clamp(centerX + areaSize / 2, -1000, 1000);
        int top = clamp(centerY - areaSize / 2, -1000, 1000);
        int bottom = clamp(centerY + areaSize / 2, -1000, 1000);

        return new Rect(left, top, right, bottom);
    }

    private void handleFocusMetering(final MotionEvent event) {
        Camera mCamera = CameraEngine.getCamera();
        Rect focusRect = calculateTapArea(event.getX(), event.getY(), 1f);
        Rect meteringRect = calculateTapArea(event.getX(), event.getY(), 1.5f);
        Camera.Parameters parameters = mCamera.getParameters();
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);

        if (parameters.getMaxNumFocusAreas() > 0) {
            List<Camera.Area> focusAreas = new ArrayList<Camera.Area>();
            focusAreas.add(new Camera.Area(focusRect, 1000));
            parameters.setFocusAreas(focusAreas);
        }

        if (parameters.getMaxNumMeteringAreas() > 0) {
            List<Camera.Area> meteringAreas = new ArrayList<Camera.Area>();
            meteringAreas.add(new Camera.Area(meteringRect, 1000));
            parameters.setMeteringAreas(meteringAreas);
        }

        try {
            mCamera.setParameters(parameters);
            updateFocusUI();
            mCamera.autoFocus(new Camera.AutoFocusCallback() {
                @Override
                public void onAutoFocus(boolean b, Camera camera) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setState(State state) {
        this.state = state;
    }

    */
/**
     * 聚焦按钮动画
     *//*

    private void updateFocusUI() {
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mIvFocus.getLayoutParams();
        params.setMargins(mFocusX - 50, mFocusY - 50, 0, 0);
        mIvFocus.setLayoutParams(params);
        mIvFocus.setVisibility(ImageView.VISIBLE);
        // 属性动画
        AnimatorSet set = new AnimatorSet();
        ObjectAnimator oaX = ObjectAnimator.ofFloat(mIvFocus, "scaleX", 1.0f, 1.1f);
        ObjectAnimator oaY = ObjectAnimator.ofFloat(mIvFocus, "scaleY", 1.0f, 1.1f);
        ObjectAnimator oaX2 = ObjectAnimator.ofFloat(mIvFocus, "scaleX", 1.1f, 0.9f);
        ObjectAnimator oaY2 = ObjectAnimator.ofFloat(mIvFocus, "scaleY", 1.1f, 0.9f);
        ObjectAnimator oaX3 = ObjectAnimator.ofFloat(mIvFocus, "scaleX", 0.9f, 1.0f);
        ObjectAnimator oaY3 = ObjectAnimator.ofFloat(mIvFocus, "scaleY", 0.9f, 1.0f);
        set.play(oaX).with(oaY);
        set.play(oaX).before(oaX2).before(oaY2);
        set.play(oaX2).before(oaX3).before(oaY3);
        set.setDuration(300);
        set.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {

            }

            @Override
            public void onAnimationEnd(Animator animator) {
                mIvFocus.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        set.start();
    }

    // 监听空事件
    private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {
        String SYSTEM_REASON = "reason";
        String SYSTEM_HOME_KEY = "homekey";
        String SYSTEM_HOME_KEY_LONG = "recentapps";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_REASON);
                if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
                    //表示按了home键,程序到了后台
                    //Toast.makeText(getApplicationContext(), "home", Toast.LENGTH_SHORT).show();
                    if (isRecording) {
                        stopRecording();
                    }
                } else if (TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)) {
                    //表示长按home键,显示最近使用的程序列表
                }
            }
        }
    };

    */
/**
     * ==========数据写入写出监听==============
     *//*

    @Override
    public void onRecordStatus(boolean isRecording, String path, String name) {
        if (isRecording) { // 开始
            tv_note.setVisibility(View.INVISIBLE);
            btn_ok.setVisibility(View.GONE);
            ImayUtils.deleteMovFile(mContxt, videoUrl);
            progressStatus = 0;
            mProgressView.setCurrentState(VideoProgressView.State.DELETE);
            mProgressView.clearTimeList();
            mProgressView.setCurrentState(VideoProgressView.State.START);
        } else { // 停止
            if (progressStatus >= 5) { //
                videoUrl = path;
                videoName = name;
                tv_note.setVisibility(View.VISIBLE);
                mProgressView.setCurrentState(VideoProgressView.State.PAUSE);
                mProgressView.putTimeList(progressStatus * 100);
                //progressStatus--;
            } else {
                ImayUtils.deleteMovFile(mContxt, path);
                tv_note.setVisibility(View.INVISIBLE);
                progressStatus = 0;
                mProgressView.setCurrentState(VideoProgressView.State.DELETE);
                mProgressView.clearTimeList();
                mTvRecordTime.setText("60.0");
            }
        }
    }

    @Override
    public void onPrepared() {

    }

    @Override
    public void onStarted() {
        muxering = true;
        mHandler.post(progress);
    }

    @Override
    public void onProgress() {

    }

    @Override
    public void onFinished() {
        muxering = false;
    }

    // 进度条
    Runnable progress = new Runnable() {
        @Override
        public void run() {
            // handler自带方法实现定时器
            if (progressStatus < 600 && isRecording && !recordFinish) {
                mHandler.postDelayed(progress, 100);
                progressStatus = progressStatus + 1;
                mHandler.sendEmptyMessage(0);
            }
            // 如果剩余时间过短，禁止录制操作
            int freeTime = 600 - progressStatus;
            if (freeTime <= 0) {
                mHandler.sendEmptyMessage(3);
            }
        }
    };

    */
/**
     * 确认
     *//*

    private void clickOk() {
        */
/**
         * 当LoadingDialog为100时才结束控制
         *//*

        int time = 1000;
        if (progressStatus >= 500) {
            time = 1000;
        } else if (progressStatus < 500 && progressStatus >= 400) {
            time = 800;
        } else if (progressStatus < 400 && progressStatus >= 300) {
            time = 600;
        } else {
            time = 400;
        }
        Log.v(TAG, time + "");
        LoadingDialogFragment.show(this, getFragmentManager(), time, new LoadingDialogFragment.OnLoadingListener() {
            @Override
            public void onShow() {
                new Thread(muercheck).start();
            }

            @Override
            public void onDimiss() {
                if (progressStatus == 0) {
                    Toast.makeText(mContxt, R.string.message_file_error, Toast.LENGTH_SHORT).show();
                    mHandler.sendEmptyMessage(6);
                } else {
                    mHandler.sendEmptyMessage(2);
                }
            }
        });
    }

    // 等待写入完成
    Runnable muercheck = new Runnable() {
        @Override
        public void run() {
            try {
                boolean isWaiter = false;
                while (muxering) {
                    Log.d(TAG, "muxering----" + muxering);
                    Thread.sleep(200);
                    isWaiter = true;
                }
                //url = manager.compose();
                if (videoUrl == null) {
                    mHandler.sendEmptyMessage(4);
                }
                //MovieInfo movieInfo = manager.getMovieInfo();
                if (isWaiter) {
                    Thread.sleep(200);
                }
                final Bitmap bitmap = ImayUtils.getVideoThumbnail(VideoRecordActivity.this, videoUrl);
                if (bitmap != null) {
                    //File file = ImayUtils.getOutputMediaFile(mContxt, ImayUtils.MEDIA_TYPE_VIDEO);
                    //final String path = file.getAbsolutePath();
                    imagePath = ImayUtils.bitmapToLocal(VideoRecordActivity.this, bitmap);
                    bitmap.recycle();
                    Runtime.getRuntime().gc();
                    if (!TextUtils.isEmpty(videoUrl)) {
                        //ImayUtils.deleteMovFile(mContxt, videoUrl);
                        mHandler.sendEmptyMessage(5);
                    } else { //视频损坏， 重新加载
                        mHandler.sendEmptyMessage(4);
                    }
                    // 视频压缩
//                    editor.executeVideoCompress(videoUrl, path, new FFmpegKit.KitInterface() {
//                        @Override
//                        public void onStart() {
//                            Log.i("FFmpegKit", "onStart");
//                        }
//
//                        @Override
//                        public void onProgress(int progress) {
//                            Log.i("FFmpegKit", "onProgress-----" + progress);
//                        }
//
//                        @Override
//                        public void onEnd(int result) {
//                            Log.i("FFmpegKit", "onEnd");
//                            imagePath = ImayUtils.bitmapToLocal(VideoRecordActivity.this, bitmap);
//                            bitmap.recycle();
//                            Runtime.getRuntime().gc();
//                            if (!TextUtils.isEmpty(path)) {
//                                ImayUtils.deleteMovFile(mContxt, videoUrl);
//                                videoUrl = path;
//                                mHandler.sendEmptyMessage(5);
//                            } else { //视频损坏， 重新加载
//                                mHandler.sendEmptyMessage(4);
//                            }
//                        }
//                    });
                    */
/**
                     * 视频压缩
                     *//*

                    */
/*editor.executeVideoCompressMediaMuxer(videoUrl, path, new IProgressListener() {
                        @Override
                        public void onMediaStart() {
                        }

                        @Override
                        public void onMediaProgress(float v) {
                        }

                        @Override
                        public void onMediaDone() {
                            imagePath = ImayUtils.bitmapToLocal(VideoRecordActivity.this, bitmap);
                            bitmap.recycle();
                            Runtime.getRuntime().gc();
                            if (!TextUtils.isEmpty(path)) {
                                ImayUtils.deleteMovFile(mContxt, videoUrl);
                                videoUrl = path;
                                mHandler.sendEmptyMessage(5);
                            } else { //视频损坏， 重新加载
                                mHandler.sendEmptyMessage(4);
                            }
                        }

                        @Override
                        public void onMediaPause() {
                        }

                        @Override
                        public void onMediaStop() {
                        }

                        @Override
                        public void onError(Exception e) {
                            e.printStackTrace();
                        }
                    });*//*

                } else {
                    mHandler.sendEmptyMessage(4);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
}
*/
